# -*- coding: utf-8 -*-
import pprint
import urllib,urllib2,cookielib
import re,time,random

username = 'admin'  #改成自己的用户名
passwd = 'admin' #改成自己的密码

def GetDeviceStatus(deviceid):
    '''这个就是登录脚本'''
    print 'try to login...'
 
    #登录需要准备cookie
    cookie=cookielib.CookieJar()
    opener = urllib2.build_opener(urllib2.HTTPCookieProcessor(cookie), urllib2.HTTPHandler)
    urllib2.install_opener(opener)
 
    #先获取verycd的loginsubmit串，用于填表
    loginform = urllib2.urlopen('http://www.qinyi365.com/lock/www/index.php/user/login').read()
    fk = re.compile(r'name="loginsubmit" value="(.*)"').findall(loginform)[0]
 
    #好的，现在填表
    postdata=urllib.urlencode({'username':username,
                           'password':passwd,
                           'loginsubmit':'登  陆'
    })
    req = urllib2.Request(
        url = 'http://www.qinyi365.com/lock/www/index.php/user/login',
        data = postdata
    )
 
    #填header，伪装成正常浏览访问，这是一种写法，也可以用我之前那篇文章的写法，更有条理一点
    req.add_header('User-Agent','Mozilla/5.0 (Windows; U; Windows NT 5.1; en-US; rv:1.9.1.9) Gecko/20100315 Firefox/3.5.9 ( .NET CLR 3.5.30729)')
    req.add_header('Accept','text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8')
    req.add_header('Accept-Encoding','gzip,deflate')
    req.add_header('Accept-Charset','ISO-8859-1,utf-8;q=0.7,*;q=0.7') 
    #交登录表，然后就登录成功了
    result = urllib2.urlopen(req).read()
    #pprint.pprint( result)
#    print '...login succeed!'
#    loginform = urllib2.urlopen('http://www.qinyi365.com/lock/www/index.php/index').read()
#    print loginform
    loginform = urllib2.urlopen('http://www.qinyi365.com/lock/www/index.php/terminal/edit/id/%s'%(deviceid)).read()
    status = re.compile(r'id="TERMINAL_STATE" size="12" value="(.*)"').findall(loginform)[0]
    return status
